//
//  CNNewsViewController.m
//  BeeQuick_19
//
//  Created by clinging on 16/9/25.
//  Copyright © 2016年 CN Team. All rights reserved.
//

#import "CNMineMessageController.h"
#import "Masonry.h"
#import "CNMineSystermMessageBottomCell.h"
#import "CNMineSystermMessageTopCell.h"
#import "DSHTTPClient.h"
#import "CNMineSystemMessageModel.h"
static NSString *TopID = @"topCell";
static NSString *BottomID = @"bottomCell";
@interface CNMineMessageController ()<UIScrollViewDelegate,UITableViewDelegate,UITableViewDataSource>
@property(weak,nonatomic)UITableView *systemMessageTableView;
@property(weak,nonatomic)UIView *userMessageView;
@property(weak,nonatomic)UIScrollView *scrollView;
@property(weak,nonatomic)UISegmentedControl *segmentedControl;
@property(weak,nonatomic)UIButton *showBtn;
@property(assign,nonatomic)BOOL buttonIsSelected;
@property(assign,nonatomic)NSInteger selectedSection;
@end

@implementation CNMineMessageController{
    NSArray <CNMineSystemMessageModel *>*_messageList;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    //avigationbar需要做这个处理才不会覆盖下面的视图，
    self.edgesForExtendedLayout = UIRectEdgeNone;
    
    [self loadData];
    
    [self setUpUI];
}

- (void)loadData{
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    
    [param setValue:@"10" forKey:@"call"];
    
    
    [DSHTTPClient postUrlString:@"SystemMessage.json.php" withParam:param withSuccessBlock:^(id data) {
        NSMutableArray *tempArr = [[NSMutableArray alloc]init];
        NSArray *modelArr = [data valueForKey:@"data"];
        [modelArr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            CNMineSystemMessageModel *model = [[CNMineSystemMessageModel alloc]init];
            model = [CNMineSystemMessageModel initWithDictionary:obj];
            [tempArr addObject:model];
        }];
        _messageList = tempArr.copy;
        [self.systemMessageTableView reloadData];
        
    } withFailedBlock:^(NSError *error) {
        NSLog(@"%@",error);
    } withErrorBlock:^(NSString *message) {
        NSLog(@"%@",message);
    }];
    
    
}

- (void)setUpUI{
    NSArray *segArr = @[@"系统消息",@"用户消息"];
    //    segment.selectedSegmentIndex是segment的item下标，通过下标的取值搞事情
    UISegmentedControl *seg = [[UISegmentedControl alloc]initWithItems:segArr];
    //    seg.segmentedControlStyle = UISegmentedControlStyleBar;
    seg.backgroundColor = [UIColor whiteColor];
    
    seg.selectedSegmentIndex = 0;
    seg.tintColor = [UIColor colorWithRed:255/255.0 green:216/255.0 blue:0/255.0 alpha:1];
    //改变普通状态属性
    NSDictionary * normalTextAttributes = @{NSFontAttributeName : [UIFont systemFontOfSize:12.0f],NSForegroundColorAttributeName : [UIColor grayColor]};
    [seg setTitleTextAttributes:normalTextAttributes forState:UIControlStateNormal];
    
    // 选中状态下
    NSDictionary * selctedTextAttributes = @{NSFontAttributeName : [UIFont boldSystemFontOfSize:15.0f],NSForegroundColorAttributeName : [UIColor blackColor]};
    [seg setTitleTextAttributes:selctedTextAttributes forState:UIControlStateSelected];
    
    
    self.navigationItem.titleView = seg;
    _segmentedControl = seg;
    [_segmentedControl addTarget:self action:@selector(segmentedControlDidSelected:) forControlEvents:UIControlEventValueChanged];
    UIScrollView *scrollView = [self setContentForScrollView];
    [self.view addSubview:scrollView];
    
    [scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(self.view);
        make.top.equalTo(self.view);
    }];
    _scrollView = scrollView;
}

- (void)segmentedControlDidSelected:(id)sender{
    CGFloat offsetx = self.scrollView.bounds.size.width * _segmentedControl.selectedSegmentIndex;
    [self.scrollView  setContentOffset:CGPointMake(offsetx, 0) animated:YES];
    
}

- (UIScrollView *)setContentForScrollView{
    UIScrollView *scrollView = [[UIScrollView alloc]initWithFrame:self.view.bounds];
    scrollView.backgroundColor = [UIColor lightGrayColor];
    scrollView.showsVerticalScrollIndicator = NO;
    scrollView.showsHorizontalScrollIndicator = NO;
    scrollView.pagingEnabled = YES;
    scrollView.bounces = NO;
    scrollView.delegate = self;
    
    UITableView *systemMessage = [[UITableView alloc]initWithFrame:scrollView.bounds style:UITableViewStyleGrouped];
    systemMessage.delegate = self;
    systemMessage.dataSource = self;
    //自动计算行高
    systemMessage.estimatedRowHeight = 50;
    systemMessage.rowHeight = UITableViewAutomaticDimension;
    //触摸延迟关闭
    systemMessage.delaysContentTouches = NO;
    systemMessage.backgroundColor = [UIColor colorWithRed:239/255.0 green:239/255.0 blue:239/255.0 alpha:1];
    
    //注册cell
    [systemMessage registerClass:[CNMineSystermMessageTopCell class] forCellReuseIdentifier:TopID];
    [systemMessage registerClass:[CNMineSystermMessageBottomCell class] forCellReuseIdentifier:BottomID];
    _systemMessageTableView = systemMessage;
    
    UIView *userMessage = [[UIView alloc]init];
    _userMessageView = userMessage;
    userMessage.backgroundColor = [UIColor colorWithRed:239/255.0 green:239/255.0 blue:239/255.0 alpha:1];
    UIImageView *noMessageImg = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"v2_my_message_empty"]];
    [userMessage addSubview:noMessageImg];
    [noMessageImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(userMessage).offset(150);
        make.left.equalTo(userMessage).offset(295/2);
        make.size.mas_equalTo(CGSizeMake(80, 80));
    }];
    UILabel *noMessageLB = [[UILabel alloc]init];
    noMessageLB.text = @"~~~并没有消息~~~";
    [userMessage addSubview:noMessageLB];
    [noMessageLB mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(noMessageImg);
        make.top.equalTo(noMessageImg.mas_bottom).offset(10);
    }];
    
    
    
    NSArray <UIView *>*arrM = @[systemMessage,userMessage];
    [arrM enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [scrollView addSubview:obj];
    }];
    
    [arrM mas_distributeViewsAlongAxis:MASAxisTypeHorizontal withFixedSpacing:0 leadSpacing:0 tailSpacing:0];
    [arrM mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.equalTo(scrollView);
        make.top.bottom.equalTo(scrollView);
    }];
    
    return scrollView;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    CGFloat offsetX = scrollView.contentOffset.x;
    if (offsetX >= self.view.bounds.size.width/2) {
        self.segmentedControl.selectedSegmentIndex = 1;
    }else if (offsetX <= self.view.bounds.size.width/2){
        self.segmentedControl.selectedSegmentIndex = 0;
    }
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 2;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (_buttonIsSelected) {
        if (indexPath.section == _selectedSection && indexPath.row == 1) {
            return self.systemMessageTableView.rowHeight;
        }
        return 40;
    }
    else {
        return 40;
    }
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) {
        CNMineSystermMessageTopCell *cell = [tableView dequeueReusableCellWithIdentifier:TopID forIndexPath:indexPath];
        cell.titleLB.text = _messageList[indexPath.section].title;
        
        _showBtn = cell.showBtn;
        self.buttonIsSelected = NO;
        [cell.showBtn addTarget:self action:@selector(showTotalBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        
        [_showBtn setTitle:@"显示全部" forState:UIControlStateNormal];
        [_showBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        
        return cell;
    }else{
        CNMineSystermMessageBottomCell *cell = [tableView dequeueReusableCellWithIdentifier:BottomID forIndexPath:indexPath];
        
        cell.messageLabel.text = _messageList[indexPath.section].content;
        return cell;}
}

- (void)showTotalBtnClick:(UIButton *)btn{
    
    NSInteger section = [[self.systemMessageTableView indexPathForCell:(UITableViewCell *)[[btn superview] superview]] section];
    _selectedSection = section;
    _buttonIsSelected = !_buttonIsSelected;
    btn.selected = _buttonIsSelected;
    if (_buttonIsSelected) {
        
        [btn setTitle:@"收起" forState:UIControlStateSelected];
        [btn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateSelected];
        [self.systemMessageTableView beginUpdates];
        [self.systemMessageTableView endUpdates];
    }else{
        [btn setTitle:@"显示全部" forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [self.systemMessageTableView beginUpdates];
        [self.systemMessageTableView endUpdates];
    }
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
